package com.duapk.index.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import au.com.bytecode.opencsv.CSVReader;

/**
 * IO操作工具类
 * @Package: com.duapk.index.util
 * @ClassName: IOUtils
 * @author: jiangzheng
 * @date: Apr 5, 2011 4:53:56 PM
 *
 */
public class IOUtils {

	/**
	 * 删除指定的目录及其目录下面的子目录和文件
	 * 
	 * @param dir
	 *            目录对象
	 */
	public static void deleteFolder(File dir) {
		if (dir == null || !dir.exists()) {
			return;
		}
		File filelist[] = dir.listFiles();
		int listlen = filelist.length;
		for (int i = 0; i < listlen; i++) {
			if (filelist[i].isDirectory()) {
				deleteFolder(filelist[i]);
			} else {
				filelist[i].delete();
			}
		}
		dir.delete();// 删除当前目录
	}

	/**
	 * 删除指定的目录及其目录下面的子目录和文件
	 * 
	 * @param dirPath
	 *            目录路径
	 */
	public static void deleteFolder(String dirPath) {
		File file = new File(dirPath);
		deleteFolder(file);
	}

	/**
	 * 读取一个目录中的所有文件的数据
	 * 
	 * @param dirPath
	 *            目录路径
	 * @param encode
	 *            字符集编码
	 * @param acceptFiles
	 *            需要读取的文件
	 * @return
	 * @throws IOException
	 */
	public static List<String> readFiles(String dirPath, String encode,
			Set<String> acceptFiles) throws IOException {
		Set<String> datas = new HashSet<String>();
		File dir = new File(dirPath);
		if (dir.exists() && dir.isDirectory()) {
			File[] files = dir.listFiles();
			for (File file : files) {
				if (acceptFiles.contains(file.getName())) {
					datas.addAll(readFile(file, encode));
				}
			}
		}
		List<String> result = new ArrayList<String>(datas);
		Collections.sort(result);
		return result;
	}

	/**
	 * 读取文件中的数据
	 * 
	 * @param file
	 *            文件对象
	 * @param encode
	 *            字符集编码
	 * @return
	 */
	public static Set<String> readFile(File file, String encode)
			throws IOException {
		Set<String> datas = new HashSet<String>();
		CSVReader reader = null;
		try {
			reader = new CSVReader(new InputStreamReader(new FileInputStream(
					file), encode));
			String[] cols = null;
			while ((cols = reader.readNext()) != null) {
				datas.add(cols[2].trim());
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return datas;
	}
}
